<?php
/*
Plugin Name: URL Shortener
Plugin URI: http://fusedthought.com/downloads/url-shortener-wordpress-plugin/
Description: This plugin integrates multiple URL Shortening service with your WordPress.org installation. Brings a similar functionality of WordPress.com's WP.me shortlinks feature but using 3rd partly URL Shorteners. Supports own domain URL Shortener awe.sm as well. An <a href="http://fusedthought.com/downloads/addon-module-for-url-shortener-wordpress-plugin/">Addon module for additional services</a> also available.
Author: Gerald Yeo
Author URI: http://fusedthought.com
Version: 3.0-Classed
*/
/* 
 * Use "fts_show_shorturl($post)" to display link in a post
 * On Demand shortening eg: "fts_shorturl('http://www.google.com', 'supr');"
 */

global $wp_version;	
$exit_msg='URL Shortener for WordPress requires WordPress Version 2.7 or later <a href="http://codex.wordpress.org/Upgrading_WordPress">Please update!</a>';
if (version_compare($wp_version,"2.7","<")){exit ($exit_msg);}
require_once( dirname(__FILE__) . '/dependencies/class.FTShorten.2.1.php');

//main class
if ( !class_exists('WP_URL_Shortener') ) :
	class WP_URL_Shortener extends FTShorten {
	
		var $db_option = 'fts_urlfx';
		var $plugin_url;
		var $plugin_page;
		
		function is_active($plugin) {return in_array($plugin, apply_filters('active_plugins', get_option('active_plugins') ) );}}
		
//--------__construct() (maintin PHP4 Compatibility)
		function WP_URL_Shortener() {	
			$this->plugin_url = defined('WP_PLUGIN_URL') ? WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)) : trailingslashit(get_bloginfo('wpurl')) . PLUGINDIR . '/' . dirname(plugin_basename(__FILE__)); 		
			
			$options = get_option($this->db_option);

			//Publishing
			add_action('publish_to_publish', array(&$this, 'pub_gateway'), 15);
			add_action('draft_to_publish', array(&$this, 'pub_gateway'), 15); 
			add_action('private_to_publish', array(&$this, 'pub_gateway'), 15); 
			add_action('future_to_publish', array(&$this, 'pub_gateway'), 15); 
			add_action('pending_to_publish', array(&$this, 'pub_gateway'), 15);  
			add_action('new_to_publish', array(&$this, 'pub_gateway'), 15); 
			
			//Add New
			add_action('load-post-new.php', array(&$this, 'post_meta_box'));
			add_action('load-page-new.php', array(&$this, 'page_meta_box'));
			
			//Options and Tables
			add_filter('manage_posts_columns', array(&$this, 'table_col_name'));
			add_action('manage_posts_custom_column', array(&$this, 'table_col_content'), 10, 2);
			add_filter('manage_pages_columns', array(&$this, 'table_col_name'));
			add_action('manage_pages_custom_column', array(&$this, 'table_col_content'), 10, 2);
			add_action('admin_menu', array(&$this, 'plugin_menu'));
			
			//AJAX Calls
			add_action('wp_ajax_shorturl_get', array(&$this, 'ajax_gateway'));
			
			// scripts/styles
			add_action('load-edit.php', array(&$this, 'pub_styles'));
			add_action('load-edit-pages.php', array(&$this, 'pub_styles'));
			
			//Redirections
			if($options['ownservice'] == 'yes'):
				if($options['ownservicetype'] == 'templateredirect'){
					add_action('template_redirect', array(&$this, 'template_redirect'));
				} elseif($options['ownservicetype'] == 'wprewriteredirect'){
					add_filter('generate_rewrite_rules', array(&$this, 'wprewrite_redirect'));
					add_filter('init',array(&$this, 'flushRules'));
				}
			endif;	
		}
		
//-------- for use in construct	
		function plugin_menu(){
			$this->plugin_page = add_options_page('URL Shortener', 'URL Shortener', 'administrator', 'shorturl', array(&$this, 'options_page'));
			add_action('load-'.$this->plugin_page,  array(&$this, 'options_scripts'));		
			add_action('load-'.$this->plugin_page,  array(&$this, 'options_styles'));
		}		
		function page_meta_box(){
			add_meta_box('fts-urlshortener', 'Short URL', array(&$this, 'pub_page'), 'page', 'side', 'default');
		}
		function post_meta_box(){
			add_meta_box('fts-urlshortener', 'Short URL', array(&$this, 'pub_page'), 'post', 'side', 'default');
		}
//--------publishing logic
		function pub_gateway($post){
			$options = $this->my_options();
			include( dirname(__FILE__) . '/lib/pub_gateway.php');
		}
		function url_logic($postid, $post_type = 'none', $to_tweet = true, $to_return = false){
			$options = $this->my_options();
			include( dirname(__FILE__) . '/lib/url_logic.php');
		}
		function tweet_logic($postid, $posturl){
			$options = $this->my_options();
			include( dirname(__FILE__) . '/lib/tweet_logic.php');
		}
//--------pub page
		function pub_page($post){
			$options = $this->my_options();
			include( dirname(__FILE__) . '/lib/pub_page.php');
		}
	
//--------table page
		function table_col_name($columns){
			$columns['Short_URL'] = __('Short URL');
			return $columns;
		}
		function table_col_content($column_name, $id){
			if ($column_name == "Short_URL"){
				$shorturl = get_post_meta($id, 'shorturl', true); 
				if (empty($shorturl)){$shorturl = get_post_meta($id, 'short_url', true);}
				print (!empty($short) ? '<a class="shortget" href="'.$shorturl.'" id="'.$id.'">Generated</a>' : '<a class="button shortget hidden" href="#'.$id.'" id="'.$id.'">Generate Now</a>');
			}
		}
		
//--------table style-script 
		function table_scripts(){
			$ftsuri = basename($_SERVER["SCRIPT_FILENAME"]);
			?>
			<script type="text/javascript" >
				var pt = '<?php echo $ftsuri ?>';
				var aaurl = '<?php echo admin_url('admin-ajax.php'); ?>';
				var nonce = '<?php echo wp_create_nonce('WP_URL_Shortener_AJAX');?>';
			</script>
			<?php
			wp_enqueue_script('jquery');
			wp_enqueue_script('url_shortener_table_ajax_queue', $this->plugin_url.'/lib/scripts/jquery.ajaxq.js',array('jquery'),1.0);
			wp_enqueue_script('url_shortener_table_ajax', $this->plugin_url.'/lib/scripts/table.js',array('jquery'),1.0);
		}

//--------options page		
		function options_page(){
			$action_url = $_SERVER['REQUEST_URI'];
			include( dirname(__FILE__) . '/lib/options_page.php');
		}
		
//--------Handle our options
		function my_options(){
			$options = array(		
				'urlserviceenable' => 'no',
				'urlservice' => 'none',
				'urlautogen' => 'no',
				'ownservice' => 'no',
				'ownservicetype' => 'templateredirect',
				'tweet' => 'disabled'
			);

		    $saved = get_option($this->db_option);
		
		    if (!empty($saved)) {
				foreach ($saved as $key => $option){
					$options[$key] = $option;
				}
		    }
		    if ($saved != $options){update_option($this->db_option, $options);}
		    return $options;
		}
		
//--------options style-script
		function options_scripts(){
			wp_enqueue_script('jquery');	
			wp_enqueue_script('url_shortener_options_js', $this->plugin_url.'/lib/styles/options_page.js',array('jquery'),1.0);		
		}	
		function options_styles(){
			wp_enqueue_style('url_shortener_options_css', $this->plugin_url.'/lib/styles/options_page.css');
		}

//--------AJAX Callbacks
		function ajax_gateway(){
			check_ajax_referer('WP_URL_Shortener_AJAX');
			$postid = $_POST['pid'];
			$pt = $_POST['pagetype'];
			$urlaction =  $_POST['urlaction'];
			switch ($urlaction){
				case 'generate' :
					if($pt  == 'edit.php'){$pagetype = 'post';} elseif($pt == 'edit-pages.php'){$pagetype = 'page';}	
					$result = $this->url_logic($postid, $pagetype, false, true);
					$x = new WP_AJAX_Response(array('data' => $result));
					$x->send();
					break;
				case 'delete' :
					delete_post_meta($postid, 'shorturl');
					delete_post_meta($postid, 'short_url');
					break;
				default: break;
			}
		}

//--------Redirect Options
		function template_redirect(){
			$options = $this->my_options();
			if( is_404() ){	
				$current_loc = strtolower($_SERVER['REQUEST_URI']);	
				$saved_loc = get_option('siteurl');
				$siteurl = parse_url($saved_loc);
				$path = $siteurl['path'];
				$url = str_replace($path, '', $current_loc );	
				$postid = preg_replace("/[^0-9]/", "", $url);
				if( !empty($postid)){
					$redir_to = get_permalink($postid);
					header("Location: " . $redir_to, true, 301);
				}	
			}
		}
		function wprewrite_redirect($rewrite){
			$options = $this->my_options();
			$customprefix = $options['ownserviceprefix'];
			$customprefix = ltrim($customprefix, " /");
			$customprefix = rtrim($customprefix, " ");
			$customprefix = strip_tags($customprefix);	
			
			global $wp_rewrite;	
			$ownservicerules = array();
			$regrules = $customprefix . '([0-9]+)$';
			$ownservicerules[$regrules] = 'index.php?p=' . $wp_rewrite->preg_index( 1 );	
			$wp_rewrite->rules = $ownservicerules + $wp_rewrite->rules;	
		}		
		function flushRules(){global $wp_rewrite; $wp_rewrite->flush_rules();}

//--------Theme Headers
		function theme_header(){
		}
		
//--------Set up everything
		function install() {$this->my_options();}
	}
endif;

//register
if ( class_exists('WP_URL_Shortener') ) :
	$WP_URL_Shortener = new WP_URL_Shortener();
	if (isset($WP_URL_Shortener)) {
		register_activation_hook(__FILE__, array(&$WP_URL_Shortener, 'install') );
	}
endif;

//for user themes
require_once(dirname(__FILE__) . '/lib/back_fx.php');
?>